<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Comment;
use App\users;
use DB;

use Illuminate\Support\Facades\Cookie;

class CommentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


   public function postAdd(Request $res,$fid){
    //return '1';
    //通过电影FID获得对应的用户评论数据并保存
    //print_r($res->user()->id);
    // if($_POST['content']=''){
    //     $_POST['content'] = '提示:这个家伙什么也没留下';
    // }
     $com = new Comment();
     $com->fid  = $fid;
     $com->id   = $res->user()->id;
     $com->content = $_POST['content'];
     $com->mark    = $_POST['mark']*10;
     $com->com_time = time();

     if($com->save()){
        echo json_encode('评论成功');}
     //return redirect()->action('Home\CommentController@comlist',[$fid]);
   }





   public function comlist(Request $res,$fid){
        //获取登录用户的信息
        $comlist = DB::table('comments')->where('id',$fid)->first();

        //获取正在播放影片的内容并输出到模板
        $film_infor = DB::table('films')
        ->leftjoin('film_atts','films.fid','=','film_atts.fid')
        ->where('films.fid',$fid)->first();

        //右边栏目显示最新的影片
        $new_film = DB::table('films')->limit(20)->get(); 

        //打印用户评论信息
        $msg = DB::table('comments')
        ->leftjoin('users','comments.id','=','users.id')
        ->leftjoin('user_atts','users.id','=','user_atts.id')
        ->where('fid',$fid)->get();  

        //计算分数
     $count_mark = DB::table('comments')->where('fid',$fid)->sum('mark');
     $count_user = DB::table('comments')->where('fid',$fid)->count('id');
     if($count_user>0){
        $score = $count_mark/$count_user;
    }else{$score = 0;}
     
     //将平均分数更新到film_atts表里
     DB::table('film_atts')->where('fid',$fid)->update(['score'=>$score]);
     $film_end = DB::table('films')
                ->leftjoin('film_atts','films.fid','=','film_atts.fid')
                ->where('is_rec',1)
                ->get();   
        return view('Home/single',
                     ['com'=>$msg,
                     'film_infor'  => $film_infor,
                     'new_film'    => $new_film,
                     'film_end'    => $film_end
                    ]);
   }


}
